/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client_server.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lucas Nguyen
 */
/*
 
 */
public class Pop3 {

    Socket cs;
    BufferedReader in;
    PrintWriter out;
    ArrayList<Mail> mailList = new ArrayList<Mail>();
    String user, pass;
    int size;

    public Pop3(String user, String pass) {
        this.user = user;
        this.pass = pass;
        //size=getSize();
    }

    String send(String msg, boolean receive) {
        String rmsg = "";
        try {
            System.out.println("Client gữi:" + msg);
             System.out.println("--------");
            if (msg.equals("\n")) {
                out.println();
            } else {
                out.println(msg);
            }
            if (receive) {
                rmsg = in.readLine();
                System.out.println("Server trả lời:" + rmsg);
                 System.out.println("--------");
            }
        } catch (IOException ex) {
            Logger.getLogger(Pop3.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rmsg;
    }

    int getSize() {
        try {
            cs = new Socket("nhom5.no-ip.org", 110);
            in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
            out = new PrintWriter(cs.getOutputStream(), true);
            send("USER " + user, true);
            send("PASS " + pass, true);
            send("STAT", true);
            String msg = send("SIZE", true);
            send("QUIT", true); // đóng mail
            send("QUIT", true);// đóng của server...
            in.close(); // ngắt kết nối
            out.close();
            cs.close();// ngắt kết nối socket
            String[] s = msg.split(" ");
            int n = Integer.parseInt(s[2]);
            return n;
        } catch (UnknownHostException ex) {
            Logger.getLogger(Pop3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Pop3.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    void getMail() {
        try {
            cs = new Socket("nhom5.no-ip.org", 110);
            in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
            out = new PrintWriter(cs.getOutputStream(), true);
            send("USER " + user, true); // gữi tên tài khoản lên server
            send("PASS " + pass, true);// gữi pass -- xữ lý bằng hàm send
            send("STAT", true);
            for (int i = 1; i <= size; i++) {
                send("RETR " + i, true);
                String content = "";
                String from = "";
                String to = "";
                String subject = "";
                boolean begin = false;
                while (true) {
                    String msg = in.readLine();
                    if (msg.equals(".")) {
                        break;
                    }
                    String msg1 = msg.toLowerCase();
                    if (msg1.startsWith("from:")) {
                        from = msg.substring(5);
                    }
                    if (msg1.startsWith("to:")) {
                        to = msg.substring(3);
                    }
                    if (msg1.startsWith("subject:")) {
                        subject = msg.substring(8);
                    }
                    if (begin) {
                        content += msg + "\n";
                    }
                    if (msg.equals("")) {
                        begin = true;
                    }
                }
               
                mailList.add(new Mail(from, to, subject, content));
                 send("QUIT", true);
                in.close();
                 out.close();
                cs.close();
            }
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(Pop3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Pop3.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void viewMail(int i) {
        Mail mail = mailList.get(i);
        System.out.println("--------------------------------------");
        System.out.println("From: " + mail.from);
        System.out.println("To: " + mail.to);
        System.out.println("Subject: " + mail.subject);
        System.out.print("Content:\n" + mail.content);
        System.out.println("--------------------------------------");
    }

    public static void main(String[] args) throws Exception {
        final Pop3 pop = new Pop3("hoangthach@nhom5.no-ip.org", "1");
        pop.size = pop.getSize();
        // nếu pop.size mà lớn hơn thì mới duyệt ... nhỏ hơn hoặc bằng 0 thì xem như không có thư.
        if(pop.size > 0) 
        {
             System.out.println("size=" + pop.size);
              System.out.println("Kết thúc quá trình lấy kích thước file");
          System.out.println("---------Lấy mail--------");
             pop.getMail();
         for (int i = 0; i < pop.getSize(); i++) {
            pop.viewMail(i);
                 }
        
         
        } 
        else {
           System.out.println("Hộp thư trống");
           System.out.println("------------------------------------");

        }
       
        
       
        }
            
    

    static class Mail {

        String from, to, subject, content;

        public Mail(String from, String to, String subject, String content) {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.content = content;
        }
    }
}
